package test.demo.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ServerSocketFactory;

/**
 * @author Hinsteny
 * @date 2016/5/24
 * @copyright: 2016 All rights reserved.
 */
public class BioServer {
	private Socket socket = null;    
    private ServerSocket serverSocket = null;    

    public BioServer(int port) throws IOException {    
    	serverSocket = ServerSocketFactory.getDefault().createServerSocket(port);
    	int threadNum = 0;
        while (true) {    
        	try{
                //监听直到接受连接后返回一个新Socket对象
                socket = serverSocket.accept();//阻塞
                threadNum++;
                //new一个线程处理连接请求
                new Thread(new Worker(socket, threadNum)).start();
            }
            catch (Throwable e) {  //防止发生异常搞死服务器          
                e.printStackTrace();
            }      
        }    
    }
    
    private static class Worker implements Runnable{
    	private int threadNum;
        private Socket socket;
        
        public Worker(Socket socket, int threadNum){
            this.socket = socket;
            this.threadNum = threadNum;
            System.out.println("Start thread: " + threadNum);
        }
        
        @Override
        public void run() {
            BufferedReader reader = null;
            PrintWriter writer = null;
            
            try {
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                writer = new PrintWriter(socket.getOutputStream());
                String inputStr = reader.readLine();//没有内容会阻塞
                while(inputStr!= null && !inputStr.equals("exit")){
                    System.out.println("thread->" + threadNum + ": " + inputStr);
                    inputStr = reader.readLine();
                }
                
                writer.flush();
                
                if(writer != null){
                    writer.close();
                }
                                    
                if(reader != null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    public static void main(String[] args) {    
        try {    
            new BioServer(7777);    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
    }    
}
